<?php
/**
 * Created by PhpStorm.
 * User: lingyun
 * Date: 2018/3/26
 * Time: 16:12
 * Desc: 原料管理
 */
namespace app\store\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use app\store\model\MaterialModel;
use app\store\model\GoodsMaterialModel;
use app\store\model\MaterialStockModel;
use app\store\model\GoodsPeifangYongliao;
use app\store\model\GoodsPeifang;

class Material extends BasicAdmin{
    /**
     * @Author  lingyun
     * @Desc    商品原料
     * 2018-03-26
     */
    public function material(){
        $this->title = "原料管理";
        $table = 'GoodsMaterial';
        $get = $this->request->get();

        $map = [];
        $map['is_deleted'] = array('eq',0);
        $map['store_id'] = ['eq',session('user.store_id')];
        if(!empty($get['name'])){
            $map['name'] = array('like',"%".$get['name']."%");
        }
        if(!empty($get['cate_1'])){
            $map['first_category'] = array('like',"%".$get['cate_1']."%");
        }
        if(!empty($get['cate_2'])){
            $map['second_category'] = array('like',"%".$get['cate_2']."%");
        }
        if(!empty($get['cate_3'])){
            $map['third_category'] = array('like',"%".$get['cate_3']."%");
        }

        $db = Db::name('goods_material')->where($map);
        $sql = "select count(*) as count from ys_goods_material where is_deleted=0 and store_id=".session('user.store_id')." and stock<warn_stock";
        $num  = Db::query($sql);//查看缺货商品数量
        $category_one = db('goods_material_category')->where(['is_deleted'=>0,'level'=>1])->select();
        $category_two = db('goods_material_category')->where(['is_deleted'=>0,'level'=>2])->select();
        $category_three = db('goods_material_category')->where(['is_deleted'=>0,'level'=>3])->select();

        $yangshi = config("qiniu");

        $this->assign('category_one',$category_one);
        $this->assign('category_two',$category_two);
        $this->assign('category_three',$category_three);
        $this->assign('yangshi',$yangshi['yangshi']);          //七牛样式后缀
        $this->assign('num',$num[0]['count']);          //七牛样式后缀

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑原材料
     * 2018-03-26
     */
    public function add_edit_material(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $post['store_id'] = session('user.store_id');
            if(isset($post['id'])){     //更新
                $res1 = db('goods_material')->where(['code'=>$post['code']])->where('id','neq',$post['id'])->find();
                $res2 = db('goods_material')->where(['tiaoma'=>$post['tiaoma']])->where('id','neq',$post['id'])->find();
                if(!empty($res1)){
                    $this->error('物料编码已被占用，请重新输入','');
                }
                if(!empty($res2)){
                    $this->error('条码已被占用，请重新输入','');
                }

//                $peifang_yongliao = db('goods_peifang_yongliao')->alias('a')->join('ys_goods_peifang b','a.p_id=b.id','LEFT')->where('a.m_id',$post['id'])->field('a.*,b.chengben as p_chengben,b.chengben_price as p_chengben_price')->select();      //配方用料详情
//                $result = $this->create_update_paifeng_arr($peifang_yongliao,$post['price'],$post['chengben_price']);
//
//                $GoodsPeifangYongliaoModel = new GoodsPeifangYongliao();
//                $GoodsPeifangModel = new GoodsPeifang();
//                $GoodsPeifangYongliaoModel->saveall($result['data1']);
//                $GoodsPeifangModel->saveall($result['data2']);


                $res = db('goods_material')->update($post);
                $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
            }else{
                $res1 = db('goods_material')->where(['code'=>$post['code']])->find();
                $res2 = db('goods_material')->where(['tiaoma'=>$post['tiaoma']])->find();
                if(!empty($res1)){
                    $this->error('物料编码已被占用，请重新输入','');
                }
                if(!empty($res2)){
                    $this->error('条码已被占用，请重新输入','');
                }

                $post['addtime'] = time();
                $res = db('goods_material')->insert($post);
                $res>0?$this->success('保存成功',''):$this->error('保存失败','');
            }
        }else{
            $id = input('id');
            $info = db('goods_material')->where('id',$id)->find();
            $category_one = db('goods_material_category')->where(['is_deleted'=>0,'level'=>1])->select();
            $category_two = db('goods_material_category')->where(['is_deleted'=>0,'level'=>2])->select();
            $category_three = db('goods_material_category')->where(['is_deleted'=>0,'level'=>3])->select();

            $this->assign('id',$id);
            $this->assign('vo',$info);
            $this->assign('category_one',$category_one);
            $this->assign('category_two',$category_two);
            $this->assign('category_three',$category_three);

            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    生成更新配方详情记录
     * 2018-05-28
     */
    private function create_update_paifeng_arr($arr,$price,$chengben_price){
        $data1 = [];        //更新配方用料详情信息
        $data2 = [];        //更新配方成本数据
        foreach($arr as $k => $v){
            $data1[$k]['id'] = $v['id'];
            $data1[$k]['chengben'] = $price*$v['p_use_kg'];
            $data1[$k]['chengben_price'] = $chengben_price*$v['p_use_kg'];
            $data2[$k]['chengben'] = $v['p_chengben']+$price*$v['p_use_kg']-$v['chengben'];
            $data2[$k]['chengben_price'] = $v['p_chengben_price']+$chengben_price*$v['p_use_kg']-$v['chengben_price'];
            $data2[$k]['id'] = $v['p_id'];
        }
        return ['data1'=>$data1,'data2'=>$data2];
    }

//    /**
//     * @Author  lingyun
//     * @Desc    添加 -- 编辑成品配方
//     */
//    public function add_edit_chengpin(){
//        $request = request();
//        if($request->isPost()){
//
//        }else{
////            $material = db('')
//        }
//    }

    /**
     * @Author  lingyun
     * @Desc    删除原料
     * 2018-03-26
     */
    public function del_material(){
        $id = input('id');
        $res = db('goods_material')->where('id',$id)->update(['is_deleted'=>1]);
        $res!==false?$this->success('删除成功',''):$this->error('删除失败','');
    }

    /**
     * @Author  lingyun
     * @Desc    原料分类
     * 2018-05-25
     */
    public function material_category(){
        $this->title = "原料分类";
        $table = 'GoodsMaterialCategory';       //原料分类
        $get = $this->request->get();

        $map = [];
        $map['is_deleted'] = array('eq',0);
        if(!empty($get['name'])){
            $map['name'] = array('like',"%".$get['name']."%");
        }

        $db = Db::name('goods_material_category')->where($map);

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    添加 -- 编辑原料分类
     * 2018-05-25
     */
    public function add_edit_material_category(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
//            halt($post);
            if(isset($post['id'])){
                $res = db('goods_material_category')->update($post);
                $res!==false?$this->success('保存成功',''):$this->error('保存失败','');
            }else{
                $post['is_deleted'] = 0;
                $post['addtime'] = time();
                $res = db('goods_material_category')->insert($post);
                $res>0?$this->success('保存成功',''):$this->error('保存失败','');
            }
        }else{
            $id = input('id');
            $info = db('goods_material_category')->where('id',$id)->find();

            $this->assign('info',$info);
            $this->assign('title','编辑分类');

            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    删除原料分类
     */
    public function del_material_category(){
        $id = input('id');
        $res = db('goods_material_category')->where('id',$id)->update(['is_deleted'=>1]);
        $res!==false?$this->success('删除成功',''):$this->error('删除失败','');
    }
    /**
     * @Author  lingyun
     * @Desc    修改安全库存
     * @return array|string
     * 2018-03-26
     */
    public function change_warn(){
        $table = 'GoodsMaterial';
        return $this->_form($table, 'change_warn');
    }

    /**
     * @Author  lingyun
     * @Desc    库存警告详情
     * @return array|string
     */
    public function warn_detail(){
        $this->title = '原材料分类';
        $get = $this->request->get();
        $map['is_deleted'] = array('eq',0);
        $map['store_id'] = array('eq',session('user.store_id'));
        if(!empty($get['name'])){
            $map['name'] = array('like',"%".$get['name']."%");
        }
        if(!empty($get['cate_1'])){
            $map['first_category'] = array('like',"%".$get['cate_1']."%");
        }
        if(!empty($get['cate_2'])){
            $map['second_category'] = array('like',"%".$get['cate_2']."%");
        }
        if(!empty($get['cate_3'])){
            $map['third_category'] = array('like',"%".$get['cate_3']."%");
        }

        $db = Db::name('goods_material')->where($map)->where('stock','lt','warn_stock');
        $category_one = db('goods_material_category')->where(['is_deleted'=>0,'level'=>1])->select();
        $category_two = db('goods_material_category')->where(['is_deleted'=>0,'level'=>2])->select();
        $category_three = db('goods_material_category')->where(['is_deleted'=>0,'level'=>3])->select();

        $this->assign('category_one',$category_one);
        $this->assign('category_two',$category_two);
        $this->assign('category_three',$category_three);

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    变更库存
     * @return array|string
     * 2018-03-26
     */
    public function change_stock(){
        if(request()->isPost()){
            $data = input('post.');
            $material = Db::name('goods_material')->where('id',$data['material_id'])->find();

            $data['receive_time'] = time();
            // $data['price'] = $material['price'];
            unset($data['name']);
            if($data['sign'] == 1){		//入库
                $data['type'] = 1;		//类型：增加
                $data['material_type'] = 1;		//原料进货
                $data['dif_num'] = $data['del_num'] - $data['res_num'];
                $data['cur_num'] = $material['stock'] + $data['res_num'];
                // $data['signal_price'] = $material['price']*$data['res_num'];
            }else{			//报损
                $data['type'] = 2;		//类型：减少
                $data['material_type'] = 1;		//原料出库
                $data['cur_num'] =  $material['stock'] - $data['dif_num'];
                $data['del_num'] = $data['dif_num'];
                // $data['signal_price'] = $material['price']*$data['dif_num'];
                $data['dif_num'] = $data['dif_num'];
                $data['res_num'] = $data['res_num'];

                // if($data['dif_num'] > $material['stock']){
                //     $this->error('报损数不能大于当前库存','');			//报损数不能大于当前库存
                // }
            }
            $res = Db::name('goods_material')->update(['id'=>$data['material_id'],'stock'=>$data['cur_num']]);
            if($res!==false){
                $res = Db::name('material_stock_log')->insert($data);
                $res>0?$this->success('保存成功',''):$this->error('保存失败,请重试','');
            }
        }else{
            $id = input('id');
            $table = "MaterialStockLog";
            $material = Db::name('goods_material')->where('id',$id)->find();
            $this->assign('time',time());
            $this->assign('material',$material);

            return $this->_form($table, 'change_stock');
        }
    }

    /**
     * @Author  lingyun
     * @Desc    采购原材料订单
     * 2018-03-26
     */
    public function create_purchase_order(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $order_sn = create_order_sn(session('user.id'));
            $id = db('material_order')->insertGetId(['admin_id'=>session('user.id'),'price'=>$post['zongji'],'order_sn'=>$order_sn,'status'=>0,'addtime'=>time(),'type'=>$post['type']]);       //订货表单
            $arr = $this->create_arr($post,$id);        //入库数据
            db('material_stock_log')->insertAll($arr);
            $id>0?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $ids = rtrim(input('get.ids'),',');       //去掉右边的逗号
            if(empty($ids)){        //没有选择原料
                $this->error('请选择需要订货的原料','');
            }
            $material = db('goods_material')->where('id','in',$ids)->select();      //原材料

            $this->assign('material',$material);
            $this->assign('type',input('type'));
            if(input('type') == 1){         //购货
                $this->assign('title','原料购货');
            }else{                          //生产
                $this->assign('title','生产使用');
            }
            return $this->fetch('create_purchase_order');
        }
    }

    /**
     * @Author      Lingyun
     * @Description  原料进货
     * @DateTime    2018-05-24
     * @Description
     * @return      [type]     [description]
     */
    public function create_jinhuo_order(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $order_sn = create_order_sn(session('user.id'));
            $id = db('material_order')->insertGetId(['admin_id'=>session('user.id'),'order_sn'=>$order_sn,'status'=>0,'addtime'=>time(),'type'=>$post['type'],'yw_type'=>$post['yw_type'],'gys'=>$post['gys'],'store_id'=>session('user.store_id')]);       //订货表单
            $arr = $this->create_arr($post,$id);        //入库数据
            db('material_stock_log')->insertAll($arr['data']);
            db('material_order')->where('id',$id)->update(['price'=>$arr['chengben_price']]);
            $id>0?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $material = db('goods_material')->where(['is_deleted'=>0,'store_id'=>session('user.store_id')])->select();      //原材料

            $this->assign('material',$material);
            $this->assign('type',input('type'));
            if(input('type') == 1){         //购货
                $this->assign('title','原料购货');
            }else{                          //生产
                $this->assign('title','生产使用');
            }
            return $this->fetch();
        }
    }

    /**
     * @Author      Lingyun
     * @Description  原料进货
     * @DateTime    2018-05-24
     * @Description
     * @return      [type]     [description]
     */
    public function create_shengchan_order(){
        $request = request();
        if($request->isPost()){
            $post = input('post.');
            $model = new GoodsMaterialModel();
            $order_sn = create_order_sn(session('user.id'));
            $id = db('material_order')->insertGetId(['admin_id'=>session('user.id'),'order_sn'=>$order_sn,'status'=>0,'addtime'=>time(),'type'=>$post['type'],'status'=>1,'receive_time'=>time(),'yw_type'=>$post['yw_type'],'is_duizhang'=>1,'gys'=>$post['gys'],'receive_admin'=>session('user.id'),'store_id'=>session('user.store_id')]);       //订货表单
            $material = db('goods_material')->where('id','in',$post['id'])->select();
            $arr = $this->create_arr($post,$id);        //入库数据
            db('material_order')->where('id',$id)->update(['price'=>$arr['chengben_price'],'receive_price'=>$arr['chengben_price']]);
            $data_arr = [];         //更新库存数据
            $receive_price = 0;
            foreach($material as $k => $v){
                $arr['data'][$k]['cur_num'] = $v['stock'] - $arr['data'][$k]['del_num'];
                $arr['data'][$k]['receive_signal_price'] = $v['price'];
                $arr['data'][$k]['receive_price'] = $arr['data'][$k]['del_num']*$v['price'];
                $receive_price += $arr['data'][$k]['receive_price'];
                $data_arr[$k] = [
                    'id'=>$arr['data'][$k]['material_id'],
                    'stock'=>$v['stock'] - $arr['data'][$k]['del_num']
                ];
            }
            $model->saveall($data_arr);
            db('material_stock_log')->insertAll($arr['data']);
            db('material_order')->where('id',$id)->update(['receive_price'=>$receive_price]);
            $id>0?$this->success('保存成功',''):$this->error('保存失败','');
        }else{
            $material = db('goods_material')->where(['is_deleted'=>0,'store_id'=>session('user.store_id')])->select();      //原材料

            $this->assign('material',$material);
            $this->assign('type',input('type'));
            if(input('type') == 1){         //购货
                $this->assign('title','原料购货');
            }else{                          //生产
                $this->assign('title','生产使用');
            }
            return $this->fetch();
        }
    }

    /**
     * @Author  lingyun
     * @Desc    创建购货申请数据
     * @param   $arr   接受的数据
     * @param   $order_id   订单数据
     * 2018-03-26
     */
    private function create_arr($arr,$order_id){
        $data = array();        //最终数据
        $num = $arr['num'];
        $ids = $arr['id'];
        $f_ids = $ids;
        $chengben_price = 0;
        $material_price = db('goods_material')->where('id','in',$ids)->field('price,stock')->select();
        if(count($f_ids) != count(array_unique($f_ids))){
            $this->error('原材料不能重复选择','');
        }
        // $xiaoji = $arr['xiaoji'];
        // $price = $arr['price'];
        foreach($ids as $k => $v){      //生成入库数据
            $chengben_price += $num[$k]*$material_price[$k]['price'];       //成本价
            if(empty($num[$k])){
                $this->error('请输入订货数量','');
            }
            // if(empty($xiaoji[$k])){
            //     $this->error('请输入小计','');
            // }
            $data[$k]['order_id'] = $order_id;
            $data[$k]['store_id'] = 0;
            $data[$k]['material_id'] = $ids[$k];
            $data[$k]['material_type'] = 1;
            $data[$k]['price'] = $num[$k]*$material_price[$k]['price'];
            $data[$k]['signal_price'] = $material_price[$k]['price'];
            if($arr['type'] == 1){      //进货
                $data[$k]['sign'] = 1;
                $data[$k]['type'] = 1;
            }else{                      //生产
                $data[$k]['sign'] = 2;
                $data[$k]['type'] = 2;
            }
            if($arr['type'] == 2){      //生产
                $data[$k]['res_num'] = $num[$k];
                $data[$k]['remark'] = '生产使用'.$num[$k];
                $data[$k]['receive_time'] = time();
                $data[$k]['dif_num'] = 0;
//                $data[$k]['cur_num'] = $material_price[$k]['stock'] - $num[$k];
            }else{
                $data[$k]['remark'] = '';
            }
            $data[$k]['del_num'] = $num[$k];
            // $data[$k]['price'] = $xiaoji[$k];
            // $data[$k]['signal_price'] = $xiaoji[$k];
            $data[$k]['addtime'] = time();
        }
        return ['data'=>$data,'chengben_price'=>$chengben_price];
    }



    /**
     * @Author  lingyun
     * @Desc    购货订单管理
     * 2018-03-27
     */
    public function order(){
        $this->title = "购货订单";
        $table = 'MaterialOrder';
        $get = $this->request->get();

        $map = [];
        $map['a.is_deleted'] = array('eq',0);
        $map['a.store_id'] = ['eq',session('user.store_id')];
        $join = [
            ['ys_system_user b','a.admin_id=b.id','LEFT'],
            ['ys_system_user c','a.receive_admin=c.id','LEFT']
        ];
        $db = Db::name('material_order')->alias('a')->join($join)->field('a.*,b.realname as create_admin,c.realname as receive_admin')->where($map)->order('a.id desc');
        if(!isset($get['status'])){
            if(!empty($get['order_sn'])){
                $map['a.order_sn'] = array('eq',$get['order_sn']);
                $db->where($map);
            }
            if(isset($get['date']) && $get['date'] !== '') {
                list($start, $end) = explode('-', str_replace(' ', '', $get['date']));
                $start = $start."  00:00:00";		$end = $end." 23:59:59";
                $start = strtotime($start);			$end = strtotime($end);
                $db->whereBetween('a.addtime',["{$start}", "{$end}"]);
            }
        }else{
            $db->where(['a.is_deleted'=>0,'a.status'=>$get['status']]);
        }
        $sql = "select count(*) as count from ys_material_order where is_deleted=0 and store_id=".session('user.store_id')." and status=0";
        $num  = Db::query($sql);//查看缺货商品数量

        $yangshi = config("qiniu");

        $this->assign('yangshi',$yangshi['yangshi']);          //七牛样式后缀
        $this->assign('new_order',$num[0]['count']);          //七牛样式后缀

        return parent::_list($db);
    }

    /**
     * @Author  lingyun
     * @Desc    订单详情
     * 2018-03-27
     */
    public function order_detail(){
        $model = new MaterialModel();
        $id = input('id');

        $order = $model->get_order($id);            //订单信息
        $list = $model->order_detail($id);          //订单详情

        $this->assign('id',$id);
        $this->assign('order',$order);
        $this->assign('list',$list);
        $this->assign('title','订单详情');

        return $this->fetch('order_detail');
    }

    /**
     * @Author  lingyun
     * @Desc    处理原料订单
     * 2018-03-27
     */
    public function deal_order(){
        $request = request();
        $model = new MaterialModel();
        $goodsmaterialmodel = new GoodsMaterialModel();
        $materialstockmodel = new MaterialStockModel();
        if($request->isPost()){
            $post = input('post.');
            $res = $model->deal_order($post);
            if($res['code'] == 1){
                db('material_order')->where('id',$post['order_id'])->update(['receive_price'=>$res['receive_price'],'receive_admin'=>session('user.id')]);
                $materialstockmodel->saveall($res['msg']['data1']);     //更新原料库存记录
                $goodsmaterialmodel->saveall($res['msg']['data2']);     //更新原料库存
                $this->success('处理成功',url('@admin').'#'.url('Material/order').'?spm='.input('spm'),'');
            }else{
                $this->error('处理失败',url('@admin').'#'.url('Material/order').'?spm='.input('spm'),'');
            }
        }else{
            $id = input('order_id');        //订单id
            $list = $model->order_detail($id);          //订单详情
            $order = $model->get_order($id);            //订单信息

            $this->assign('id',$id);
            $this->assign('list',$list);
            $this->assign('order',$order);
            $this->assign('title','处理订单');

            return $this->fetch('deal_order');
        }
//        $id = input('order_id');
//        $model = new MaterialModel();
//        $model->deal_order($id);        //处理订单

    }

    /**
     * @Author  lingyun
     * @Desc    导出订单详情
     * 2018-03-27
     */
    public function export_detail(){
        $id = input('order_id');
        $model = new MaterialModel();
        $model->export_detail($id);
    }

    /**
     * @Author  lingyun
     * @Desc    打印原料购货详情
     * 2018-03-27
     */
    public function print_detail(){
        $id = input('order_id');
        $model = new MaterialModel();

        $order = $model->get_order($id);            //订单信息
        $list = $model->order_detail($id);          //订单详情

        $this->assign('id',$id);
        $this->assign('order',$order);
        $this->assign('list',$list);

        return $this->fetch('print_detail');
    }


}